from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required

from .forms import LoginForm, RegisterForm
from .models import UserProfile

def login_view(request):
    if request.method != 'POST':
        form = LoginForm()
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(request, username=username, password=password)
            if user is not None:
                login(request, user)
                # 登陆成功跳转到指定页面
                return HttpResponse('登陆成功')
            else:
                # 验证不通过提示！
                return HttpResponse("账号或者密码错误！")
    return render(request, 'users/login.html', {'form': form})

def register(request):
    if request.method != 'POST':
        form = RegisterForm()
    else:
        form = RegisterForm(request.POST)
        if form.is_valid():
            new_user = form.save(commit=False)
            new_user.set_password(form.cleaned_data['password'])
            new_user.save()
            return redirect('users:login')
    context = {'form': form}
    return render(request, 'users/register.html', context)

@login_required(login_url='users:login')   # 设置登录后才能访问，如果没有登陆，就跳转到登录界面
def user_profile(request):
    user = UserProfile.objects.get(username=request.user)
    return render(request, 'users/user_profile.html', {'user': user})
